const CACHE_NAME = `G9.GAME APP`;
const PRECACHE_URLS = [
  '/',
  '/logo.png',
  '/logo-192.png',
  '/index.html',
];

// service-worker.js
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        // return cache.addAll(PRECACHE_URLS);
      }),
  );
});

self.addEventListener('fetch', (event) => {
  let url;
  try {
    url = new URL(event.request.url);
  }
  catch (error) {
    return;
  }
  if (event.request.method !== 'GET' || url.origin !== self.location.origin)
    return;
  const pathname = url.pathname;
  if (PRECACHE_URLS.includes(pathname)) {
    event.respondWith(
      caches.match(event.request).then((cachedResponse) => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return fetch(event.request).then((networkResponse) => {
          if (networkResponse && networkResponse.status === 200) {
            const clonedResponse = networkResponse.clone();
            caches.open(CACHE_NAME).then((cache) => {
              cache.put(event.request, clonedResponse).catch((err) => {
                console.error('Failed to cache the response:', err);
              });
            });
            return networkResponse;
          }
          return networkResponse;
        });
      }),
    );
  }
  else {
    event.respondWith(fetch(event.request));
  }
});

self.addEventListener('push', (event) => {
  if (event.data) {
    const notificationData = event.data.json();
    const title = notificationData.title;
    const body = notificationData.body;
    const url = notificationData.url;
    const icon = notificationData.icon;

    if (self.registration) {
      const notificationPromise = self.registration.showNotification(title, {
        body,
        icon,
        data: { url },
      });
      event.waitUntil(notificationPromise);
    }
  }
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const url = event.notification.data.url;
  if (url) {
    event.waitUntil(
      clients.openWindow(url),
    );
  }
});
